import { useState, useEffect } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { currentUserCan } from "../lib/utilities";
import { useVulnerabilityColor } from '../lib/customHooks';
import { WithAuth } from "../lib/authutils";
import { ModalErrorMessage, StyleLabel } from '../lib/formstyles'
import { FormSkeleton } from '../components/skeletons'
import CKWrapper from '../components/ckwrapper';
import { Vulnerability, Project } from '../lib/data/definitions'
import * as api from '../lib/data/api';
import Button from '../components/button';

//function to break the vulnerabilitycvssvector into an object for form radio buttons
type CVSSReturn = {
  success?: boolean
  errorType?: string
  baseMetricScore?: string | number | undefined;
  baseSeverity?: string | number | undefined;
  environmentalMetricScore?: string | number | undefined;
  environmentalSeverity?: string | number | undefined;
  temporalMetricScore?: string | number | undefined;
  temporalSeverity?: string | number | undefined;
  vectorString?: string | number | undefined;
}
interface VulnerabilityViewProps {
  projectId?: number
}

function VulnerabilityView(props: VulnerabilityViewProps): JSX.Element {
  //calculator is loaded in the base index.html from https://www.first.org/cvss/calculator/cvsscalc31.js
  const calculate: ((vector: string | null | undefined) => CVSSReturn) | undefined = window?.CVSS31.calculateCVSSFromVector;
  const [project, setProject] = useState<Project | null>(null)
  const {id} = useParams()
  const { projectId } = props
  const [loading, setLoading] = useState(true)
  const [loadingError, setLoadingError] = useState(false)
  //for display of severity
  const [meaning, setMeaning] = useState('None')
  const [color, setColor] = useState('blue-500')
  const [vuln, setVuln] = useState<Vulnerability | null>(null)
  const navigate = useNavigate()
  
  let calculatedScore: CVSSReturn = {}
  useEffect(() => {
    const loadData = async () => {
      try {   
        let vData: Vulnerability
        vData = await api.getVulnerability(String(id)) as Vulnerability;
        // if(projectId) {
        //   vData = await api.getProjectVulnerability(String(id)) as ProjectVulnerability;
        // } else {
        //   vData = await api.getVulnerability(String(id)) as Vulnerability;
        // }
        setVuln(vData);
        calculatedScore = calculate(vData.cvssvector)
        const [_meaning, _color] = useVulnerabilityColor(vData.vulnerabilityseverity as string)
        setMeaning(_meaning)
        setColor(_color)
        
      } catch (error) {
          //the api returns 404 if there are no instancess, which is not technically an error, 
        // it just means we haven't saved any instances
        if (typeof error === 'string' && !error.includes('404')) {
          console.error("Error fetching vulnerability data:", error);
          setLoadingError(true);    
        }
      } finally {
        setLoading(false);
      }
    }
    const loadProject = async () => {
      if (projectId) {
        setLoading(true);
        try {
          const projectData = await api.getProject(String(projectId)) as Project;
          setProject(projectData as Project);
        } catch (error) {
          setLoadingError(true);
          // Handle error fetching data
        } finally {
          setLoading(false);
        }
      }
    }
    loadData();
    if(projectId) {
      loadProject();
    }
  }, []);
  
  const heading = projectId ? "Project Vulnerablity" : "Vulnerability"
    
  if (loadingError) return <ModalErrorMessage message={"Error loading vulnerability"} />
  if(loading) return <FormSkeleton numInputs={6} className='max-w-lg'/>
  
  return (
      <div  className="w-[840px] flex-1 rounded-lg min-h-[800px] border-black relative">
        {currentUserCan('Manage Vulnerability Data') && (
          <Button 
          className='btn bg-primary m-2 mr-0 mb-2' 
          onClick={()=> navigate(`/vulnerabilities/${vuln?.id}/edit`)}
          >
          Edit Vulnerability
        </Button>
        )}
        <h1 className="mb-6 text-2xl">
            {heading}
        </h1>
        
        {project && 
          <p className="mb-4">Project: {project.name}</p>
        }
        <div className="w-full">
          <div className="relative mb-4">
            <label 
              htmlFor="vulnerabilityname"
              className={StyleLabel}>
              Name
            </label>
              {vuln?.vulnerabilityname}
          </div>
          <div className='mb-4'>
          <label className={StyleLabel}>Score</label> 
            <span className={`text-[${color}]`}>{vuln?.cvssscore}
              {calculatedScore?.baseMetricScore} ({meaning})
            </span>
          </div>
         
          <div className="relative">
            <label 
              htmlFor="vulnerabilitydescription"
              className={StyleLabel}>
              Description
            </label>
            <div>
            <CKWrapper
                    id="description"
                    data = {vuln?.vulnerabilitydescription || ''}
                    onChange={(id: string, data: string) => {
                      console.log("Edit not allowed, read-only mode");
                  }}
                    readOnly={true}
                  />
               </div> 
          </div>
          
          <div className="relative">
            <label 
              htmlFor="vulnerabilitysolution"
              className={StyleLabel}>
              Solution
            </label>
            <div className='mt-2'>
            {vuln?.vulnerabilitysolution ? (
    <CKWrapper
                  id="description"
                  data={vuln?.vulnerabilitysolution || ''}
                  onChange={(id, data) => {
                      console.log("Edit not allowed, read-only mode");
                  }}
                  readOnly={true}
              />
          ) : (
              <div>
                  No solution provided
              </div>
          )}
            </div>
                
            
          </div>
          {vuln?.vulnerabilityreferlnk &&
          <div className="relative">
            <label 
              htmlFor="vulnerabilitylink"
              className={StyleLabel}>
              Links to more information
            </label>
            <CKWrapper
                    id="description"
                    data = {vuln?.vulnerabilityreferlnk || ''}
                    onChange={(id: string, data: string) => {
                      console.log("Edit not allowed, read-only mode");
                  }}
                    readOnly={true}
                  />
          </div>
          }
        </div>
      </div>
  );
}


export default WithAuth(VulnerabilityView);
